package com.imooc.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author: bizy
 * @date: 2020/06/21 19:30
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    //设置超时
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//    })

    @HystrixCommand(commandProperties = {
            //是否启用熔断器，默认是TURE。
            @HystrixProperty(name = "circuitBreaker.enabled", value= "true"),
            //至少10个(默认20)请求才进行百分比计算
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value= "10"),
            //半开试探休眠时间，默认值5000ms。当熔断器开启一段时间之后比如5000ms，会尝试放过去一部分流量进行试探，确定依赖服务是否恢复。
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value= "10000"),
            //错误百分比(默认值50%)
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value= "60")
    })
//    @HystrixCommand
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {
        if (number % 2 == 0) {
            return "success";
        }
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://127.0.0.1:8088/product/listForOrder",
                Arrays.asList("157875196366160022"), String.class);
//        throw new RuntimeException("发送异常了");
    }

    public String fallback() {
        return "太拥挤了，请稍后再试~~";
    }

    public String defaultFallback() {
        return "默认提示：太拥挤了，请稍后再试~~";
    }
}
